<template>
  <AIEmbedChat
    :visible.sync="dialogVisible"
    title="AI智能创建内容工厂"
    api-url="/cms/api/ai_chat/"
    handler-name="content_factory_creator"
    :context-data="getContextData()"
    :suggested-questions="suggestedQuestions"
    placeholder="请描述您的需求，例如：我是做LED灯具的工厂，想做Facebook日常营销贴文..."
    :auto-parse-json="true"
    :left-span="12"
    :right-span="12"
    @dialog-opened="handleDialogOpened"
    @json-parsed="handleJsonParsed"
    @update:visible="$emit('update:visible', $event)"
  >
    <!-- 右侧：结构化数据展示和编辑 -->
    <template #right-panel>
      <div class="factory-data-panel">
        <div class="panel-header">
          <h3>
            <i class="el-icon-magic-stick" style="color: #1EB7E6;" />
            内容工厂配置
            <el-tag v-if="currentStage" size="small" type="success" style="margin-left: 10px;">
              {{ stageNames[currentStage] }}
            </el-tag>
          </h3>
          <el-button
            type="success"
            size="small"
            icon="el-icon-check"
            :loading="saving"
            :disabled="!canSave"
            @click="saveFactory"
          >
            保存内容工厂
          </el-button>
        </div>

        <!-- 进度指示器 -->
        <el-steps :active="stageIndex" finish-status="success" align-center style="margin-bottom: 20px;">
          <el-step title="需求调研" />
          <el-step title="动态素材" />
          <el-step title="话题列表" />
          <el-step title="Prompt生成" />
          <el-step title="任务设置" />
          <el-step title="完成" />
        </el-steps>

        <el-tabs v-model="activeTab" type="card">
          <!-- Tab 1: 基本信息 -->
          <el-tab-pane label="基本信息" name="basic">
            <el-form label-width="120px" size="small">
              <el-form-item label="任务名称">
                <el-input v-model="factoryData.task_name" placeholder="例如：2024 LED工厂日常贴文" />
              </el-form-item>
              <el-form-item label="行业">
                <el-input v-model="factoryData.industry" placeholder="例如：LED照明制造" />
              </el-form-item>
              <el-form-item label="目标平台">
                <el-checkbox-group v-model="factoryData.platforms">
                  <el-checkbox label="Facebook">Facebook</el-checkbox>
                  <el-checkbox label="LinkedIn">LinkedIn</el-checkbox>
                  <el-checkbox label="Twitter">Twitter</el-checkbox>
                  <el-checkbox label="Instagram">Instagram</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <el-form-item label="内容目标">
                <el-input
                  v-model="factoryData.content_goal"
                  type="textarea"
                  :rows="3"
                  placeholder="例如：提升品牌知名度、展示产品优势、分享行业见解"
                />
              </el-form-item>
            </el-form>
          </el-tab-pane>

          <!-- Tab 2: Prompt模板 -->
          <el-tab-pane :label="`Prompt模板 ${factoryData.prompt_template ? '✓' : ''}`" name="prompt">
            <el-alert
              v-if="factoryData.prompt_template"
              title="Prompt已生成"
              type="success"
              description="您可以根据需要修改Prompt模板"
              :closable="false"
              show-icon
              style="margin-bottom: 15px;"
            />
            <el-form-item label="Prompt内容" label-width="120px">
              <el-input
                v-model="factoryData.prompt_template"
                type="textarea"
                :rows="15"
                placeholder="AI将为您生成专业的Prompt模板..."
              />
            </el-form-item>
            <div style="text-align: right;">
              <el-button
                type="primary"
                size="small"
                icon="el-icon-edit"
                style="background-color: #1EB7E6; border-color: #1EB7E6;"
                @click="askAIToOptimizePrompt"
              >
                让AI优化Prompt
              </el-button>
            </div>
          </el-tab-pane>

          <!-- Tab 3: 动态素材 -->
          <el-tab-pane :label="`动态素材 (${getTotalDynamicItems()})`" name="dynamic">
            <el-alert
              title="动态素材说明"
              type="info"
              description="动态素材会在生成内容时随机选择，让每篇帖子都有所不同"
              :closable="false"
              show-icon
              style="margin-bottom: 15px;"
            />

            <div v-if="factoryData.dynamic_content_groups && factoryData.dynamic_content_groups.length > 0">
              <el-collapse v-model="activeGroups" accordion>
                <el-collapse-item
                  v-for="(group, index) in factoryData.dynamic_content_groups"
                  :key="index"
                  :name="index"
                >
                  <template slot="title">
                    <div style="display: flex; align-items: center; width: 100%;">
                      <i class="el-icon-folder" style="margin-right: 10px; color: #E6A23C;" />
                      <span style="font-weight: bold;">{{ group.name || `动态内容组 ${index + 1}` }}</span>
                      <el-tag size="mini" style="margin-left: 10px;">{{ group.items ? group.items.length : 0 }}项</el-tag>
                      <div style="flex: 1;" />
                      <el-button
                        type="text"
                        size="small"
                        icon="el-icon-delete"
                        style="color: #F56C6C;"
                        @click.stop="removeDynamicGroup(index)"
                      >
                        删除
                      </el-button>
                    </div>
                  </template>

                  <el-form label-width="100px" size="small">
                    <el-form-item label="组名称">
                      <el-input v-model="group.name" placeholder="例如：公司优势、联系方式" />
                    </el-form-item>
                    <el-form-item label="Shortcode">
                      <el-tag>{{ topic_GROUP_ID_description_random_1 }}</el-tag>
                      <el-button
                        type="text"
                        size="small"
                        icon="el-icon-document-copy"
                        @click="copyToClipboard(`{{topic_GROUP_ID_description_random_1}}`)"
                      >
                        复制
                      </el-button>
                    </el-form-item>
                    <el-form-item label="素材列表">
                      <div
                        v-for="(item, itemIndex) in group.items"
                        :key="itemIndex"
                        style="display: flex; margin-bottom: 10px;"
                      >
                        <el-input
                          v-model="group.items[itemIndex]"
                          type="textarea"
                          :rows="2"
                          placeholder="输入素材内容"
                          style="flex: 1;"
                        />
                        <el-button
                          type="danger"
                          icon="el-icon-delete"
                          size="small"
                          style="margin-left: 10px;"
                          @click="group.items.splice(itemIndex, 1)"
                        />
                      </div>
                      <el-button
                        type="primary"
                        size="small"
                        icon="el-icon-plus"
                        @click="group.items.push('')"
                      >
                        添加素材项
                      </el-button>
                    </el-form-item>
                  </el-form>
                </el-collapse-item>
              </el-collapse>

              <div style="margin-top: 15px; text-align: center;">
                <el-button type="primary" icon="el-icon-plus" @click="addDynamicGroup">新增动态内容组</el-button>
              </div>
            </div>
            <div v-else style="text-align: center; padding: 40px;">
              <el-empty description="暂无动态素材">
                <el-button type="primary" icon="el-icon-plus" @click="addDynamicGroup">新增动态内容组</el-button>
              </el-empty>
            </div>
          </el-tab-pane>

          <!-- Tab 4: 循环列表（可选） -->
          <el-tab-pane :label="`循环列表 (${getTotalLoopItems()})`" name="loop">
            <el-form-item label="启用循环列表" label-width="120px">
              <el-switch v-model="factoryData.need_loop_content" />
              <div style="color: #909399; font-size: 12px; margin-top: 5px;">
                循环列表将为每个列表项生成不同内容（例如：多个产品系列）
              </div>
            </el-form-item>

            <div v-if="factoryData.need_loop_content">
              <div v-if="factoryData.loop_content_groups && factoryData.loop_content_groups.length > 0">
                <el-collapse v-model="activeLoopGroups" accordion>
                  <el-collapse-item
                    v-for="(group, index) in factoryData.loop_content_groups"
                    :key="index"
                    :name="index"
                  >
                    <template slot="title">
                      <div style="display: flex; align-items: center; width: 100%;">
                        <i class="el-icon-refresh" style="margin-right: 10px; color: #409EFF;" />
                        <span style="font-weight: bold;">{{ group.name || `循环列表组 ${index + 1}` }}</span>
                        <el-tag size="mini" type="info" style="margin-left: 10px;">{{ group.items ? group.items.length : 0 }}项</el-tag>
                        <div style="flex: 1;" />
                        <el-button
                          type="text"
                          size="small"
                          icon="el-icon-delete"
                          style="color: #F56C6C;"
                          @click.stop="removeLoopGroup(index)"
                        >
                          删除
                        </el-button>
                      </div>
                    </template>

                    <el-form label-width="100px" size="small">
                      <el-form-item label="列表名称">
                        <el-input v-model="group.name" placeholder="例如：产品系列、客户案例" />
                      </el-form-item>
                      <el-form-item label="列表项">
                        <div
                          v-for="(item, itemIndex) in group.items"
                          :key="itemIndex"
                          style="display: flex; margin-bottom: 10px;"
                        >
                          <el-input
                            v-model="group.items[itemIndex]"
                            placeholder="输入列表项内容"
                            style="flex: 1;"
                          />
                          <el-button
                            type="danger"
                            icon="el-icon-delete"
                            size="small"
                            style="margin-left: 10px;"
                            @click="group.items.splice(itemIndex, 1)"
                          />
                        </div>
                        <el-button
                          type="primary"
                          size="small"
                          icon="el-icon-plus"
                          @click="group.items.push('')"
                        >
                          添加列表项
                        </el-button>
                      </el-form-item>
                    </el-form>
                  </el-collapse-item>
                </el-collapse>

                <div style="margin-top: 15px; text-align: center;">
                  <el-button type="primary" icon="el-icon-plus" @click="addLoopGroup">新增循环列表组</el-button>
                </div>
              </div>
              <div v-else style="text-align: center; padding: 40px;">
                <el-empty description="暂无循环列表">
                  <el-button type="primary" icon="el-icon-plus" @click="addLoopGroup">新增循环列表组</el-button>
                </el-empty>
              </div>
            </div>
          </el-tab-pane>

          <!-- Tab 5: 话题列表 -->
          <el-tab-pane :label="`话题列表 (${factoryData.topics ? factoryData.topics.length : 0})`" name="topics">
            <el-alert
              title="话题列表说明"
              type="info"
              description="系统将为每个话题生成内容，话题数量 × 每话题发帖数 = 总发帖数"
              :closable="false"
              show-icon
              style="margin-bottom: 15px;"
            />

            <div v-if="factoryData.topics && factoryData.topics.length > 0">
              <el-table :data="factoryData.topics" border size="small" max-height="400">
                <el-table-column label="序号" type="index" width="60" />
                <el-table-column label="关键词" width="200">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.keyword" size="small" placeholder="关键词" />
                  </template>
                </el-table-column>
                <el-table-column label="标题" width="250">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.title" size="small" placeholder="标题" />
                  </template>
                </el-table-column>
                <el-table-column label="描述">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.description"
                      type="textarea"
                      :rows="2"
                      size="small"
                      placeholder="话题描述"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="80" fixed="right">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      size="small"
                      icon="el-icon-delete"
                      style="color: #F56C6C;"
                      @click="factoryData.topics.splice(scope.$index, 1)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>

              <div style="margin-top: 15px; text-align: center;">
                <el-button type="primary" icon="el-icon-plus" @click="addTopic">新增话题</el-button>
              </div>
            </div>
            <div v-else style="text-align: center; padding: 40px;">
              <el-empty description="暂无话题">
                <el-button type="primary" icon="el-icon-plus" @click="addTopic">新增话题</el-button>
              </el-empty>
            </div>
          </el-tab-pane>

          <!-- Tab 6: 任务设置 -->
          <el-tab-pane label="任务设置" name="settings">
            <el-form label-width="150px" size="small">
              <el-form-item label="每个话题发帖数">
                <el-input-number v-model="factoryData.post_every_topic" :min="-1" />
                <div style="color: #909399; font-size: 12px; margin-top: 5px;">
                  -1表示没有限制，推荐值：3-5
                </div>
              </el-form-item>
              <el-form-item label="发帖周期（天）">
                <el-input-number v-model="factoryData.post_period_day" :min="1" />
                <div style="color: #909399; font-size: 12px; margin-top: 5px;">
                  每隔N天生成新一轮内容，推荐值：7
                </div>
              </el-form-item>
              <el-form-item label="周期内发帖量">
                <el-input-number v-model="factoryData.post_number_in_period" :min="1" />
                <div style="color: #909399; font-size: 12px; margin-top: 5px;">
                  每个员工在周期内最多发帖数，推荐值：2
                </div>
              </el-form-item>
              <el-form-item label="目标员工">
                <el-radio-group v-model="factoryData.all_staff">
                  <el-radio :label="true">所有员工</el-radio>
                  <el-radio :label="false">指定标签员工</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="!factoryData.all_staff" label="员工标签">
                <el-select v-model="factoryData.staff_tag" multiple filterable allow-create placeholder="输入员工标签">
                  <el-option label="sales" value="sales" />
                  <el-option label="marketing" value="marketing" />
                  <el-option label="manager" value="manager" />
                </el-select>
                <div style="color: #909399; font-size: 12px; margin-top: 5px;">
                  只有包含所选标签的员工会收到任务
                </div>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>

        <!-- 数据摘要 -->
        <el-card v-if="factoryData.task_name" shadow="hover" style="margin-top: 20px;">
          <div slot="header">
            <i class="el-icon-data-analysis" />
            <span style="font-weight: bold; margin-left: 5px;">数据摘要</span>
          </div>
          <el-descriptions :column="2" border size="small">
            <el-descriptions-item label="任务名称">{{ factoryData.task_name }}</el-descriptions-item>
            <el-descriptions-item label="行业">{{ factoryData.industry }}</el-descriptions-item>
            <el-descriptions-item label="目标平台">{{ factoryData.platforms ? factoryData.platforms.join(', ') : '-' }}</el-descriptions-item>
            <el-descriptions-item label="Prompt模板">{{ factoryData.prompt_template ? '已生成' : '未生成' }}</el-descriptions-item>
            <el-descriptions-item label="动态素材组">{{ factoryData.dynamic_content_groups ? factoryData.dynamic_content_groups.length : 0 }}组</el-descriptions-item>
            <el-descriptions-item label="动态素材项">{{ getTotalDynamicItems() }}项</el-descriptions-item>
            <el-descriptions-item label="循环列表">{{ factoryData.need_loop_content ? '已启用' : '未启用' }}</el-descriptions-item>
            <el-descriptions-item label="话题数量">{{ factoryData.topics ? factoryData.topics.length : 0 }}个</el-descriptions-item>
            <el-descriptions-item label="每话题发帖数">{{ factoryData.post_every_topic }}</el-descriptions-item>
            <el-descriptions-item label="发帖周期">{{ factoryData.post_period_day }}天</el-descriptions-item>
            <el-descriptions-item label="预计总发帖数" :span="2">
              <el-tag type="success" size="medium">
                {{ calculateTotalPosts() }}篇
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </div>
    </template>

    <!-- 自定义footer -->
    <template #footer="{ close }">
      <el-button @click="close">关闭</el-button>
      <el-button
        type="success"
        :loading="saving"
        :disabled="!canSave"
        icon="el-icon-check"
        @click="saveFactory"
      >
        保存并创建内容工厂
      </el-button>
    </template>
  </AIEmbedChat>
</template>

<script>
import AIEmbedChat from '@/components/AIEmbedChat'
import { Post as AddAutopostgeneratetask, AddFactoryContent, SavePromptTopic } from '@/api/cms/autopostgeneratetask'

export default {
  name: 'FactoryAICreator',
  components: {
    AIEmbedChat
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      activeTab: 'basic',
      activeGroups: [],
      activeLoopGroups: [],
      saving: false,
      currentStage: 'requirement', // requirement, prompt, dynamic, loop, topics, settings, complete
      suggestedQuestions: [
        {
          title: '📝 我想创建博客文章',
          question: '我想为公司网站创建SEO优化的博客文章，涵盖行业知识、产品介绍和客户案例',
          icon: 'el-icon-document',
          color: '#409EFF'
        },
        {
          title: '🏭 我想为工厂创建Facebook日常贴文',
          question: '我是做LED照明的工厂，想创建Facebook日常营销贴文，主要展示产品优势和行业见解',
          icon: 'el-icon-s-flag',
          color: '#67C23A'
        },
        {
          title: '📱 我要做LinkedIn专业内容',
          question: '我是做机械设备的B2B企业，想在LinkedIn上发布专业技术文章和客户案例',
          icon: 'el-icon-connection',
          color: '#E6A23C'
        },
        {
          title: '🎯 我需要多平台营销内容',
          question: '我想同时在Facebook、LinkedIn和Twitter上做内容营销，覆盖更多客户',
          icon: 'el-icon-share',
          color: '#F56C6C'
        },
        {
          title: '💡 帮我了解内容工厂功能',
          question: '请介绍一下内容工厂的功能，我应该如何配置？',
          icon: 'el-icon-question',
          color: '#909399'
        }
      ],
      factoryData: {
        task_name: '',
        industry: '',
        platforms: [],
        content_goal: '',
        prompt_template: '',
        dynamic_content_groups: [],
        need_loop_content: false,
        loop_content_groups: [],
        topics: [],
        post_every_topic: 3,
        post_period_day: 7,
        post_number_in_period: 2,
        all_staff: true,
        staff_tag: []
      },
      stageNames: {
        'requirement': '需求调研',
        'dynamic': '动态素材',
        'topics': '话题列表',
        'prompt': 'Prompt生成',
        'settings': '任务设置',
        'complete': '完成配置'
      }
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    stageIndex() {
      const stages = ['requirement', 'dynamic', 'topics', 'prompt', 'settings', 'complete']
      return stages.indexOf(this.currentStage)
    },
    canSave() {
      return this.factoryData.task_name &&
             this.factoryData.prompt_template &&
             this.factoryData.topics &&
             this.factoryData.topics.length > 0
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.resetData()
      }
    }
  },
  methods: {
    handleDialogOpened() {
      console.log('AI对话框已打开')
    },
    handleJsonParsed(data) {
      console.log('AI返回的结构化数据:', data)

      // 根据AI返回的stage更新当前阶段
      if (data.stage) {
        this.currentStage = data.stage
      }

      // 合并AI返回的数据
      if (data.task_name) this.factoryData.task_name = data.task_name
      if (data.industry) this.factoryData.industry = data.industry
      if (data.platforms) this.factoryData.platforms = data.platforms
      if (data.content_goal) this.factoryData.content_goal = data.content_goal
      if (data.prompt_template) this.factoryData.prompt_template = data.prompt_template
      if (data.dynamic_content_groups) {
        this.factoryData.dynamic_content_groups = data.dynamic_content_groups
      }
      if (data.need_loop_content !== undefined) {
        this.factoryData.need_loop_content = data.need_loop_content
      }
      if (data.loop_content_groups) {
        this.factoryData.loop_content_groups = data.loop_content_groups
      }
      if (data.topics) this.factoryData.topics = data.topics
      if (data.post_every_topic) this.factoryData.post_every_topic = data.post_every_topic
      if (data.post_period_day) this.factoryData.post_period_day = data.post_period_day
      if (data.post_number_in_period) {
        this.factoryData.post_number_in_period = data.post_number_in_period
      }

      // 根据stage切换到对应的Tab
      const stageTabMap = {
        'requirement': 'basic',
        'prompt': 'prompt',
        'dynamic': 'dynamic',
        'loop': 'loop',
        'topics': 'topics',
        'settings': 'settings',
        'complete': 'basic'
      }
      if (data.stage && stageTabMap[data.stage]) {
        this.activeTab = stageTabMap[data.stage]
      }

      this.$message.success('AI已更新配置数据')
    },
    getContextData() {
      return {
        current_stage: this.currentStage,
        factory_data: this.factoryData
      }
    },
    resetData() {
      this.factoryData = {
        task_name: '',
        industry: '',
        platforms: [],
        content_goal: '',
        prompt_template: '',
        dynamic_content_groups: [],
        need_loop_content: false,
        loop_content_groups: [],
        topics: [],
        post_every_topic: 3,
        post_period_day: 7,
        post_number_in_period: 2,
        all_staff: true,
        staff_tag: []
      }
      this.currentStage = 'requirement'
      this.activeTab = 'basic'
    },
    addDynamicGroup() {
      if (!this.factoryData.dynamic_content_groups) {
        this.$set(this.factoryData, 'dynamic_content_groups', [])
      }
      this.factoryData.dynamic_content_groups.push({
        name: '',
        items: ['']
      })
    },
    removeDynamicGroup(index) {
      this.factoryData.dynamic_content_groups.splice(index, 1)
    },
    addLoopGroup() {
      if (!this.factoryData.loop_content_groups) {
        this.$set(this.factoryData, 'loop_content_groups', [])
      }
      this.factoryData.loop_content_groups.push({
        name: '',
        items: ['']
      })
    },
    removeLoopGroup(index) {
      this.factoryData.loop_content_groups.splice(index, 1)
    },
    addTopic() {
      if (!this.factoryData.topics) {
        this.$set(this.factoryData, 'topics', [])
      }
      this.factoryData.topics.push({
        keyword: '',
        title: '',
        description: ''
      })
    },
    getTotalDynamicItems() {
      if (!this.factoryData.dynamic_content_groups) return 0
      return this.factoryData.dynamic_content_groups.reduce((total, group) => {
        return total + (group.items ? group.items.length : 0)
      }, 0)
    },
    getTotalLoopItems() {
      if (!this.factoryData.loop_content_groups) return 0
      return this.factoryData.loop_content_groups.reduce((total, group) => {
        return total + (group.items ? group.items.length : 0)
      }, 0)
    },
    calculateTotalPosts() {
      const topicCount = this.factoryData.topics ? this.factoryData.topics.length : 0
      const postsPerTopic = this.factoryData.post_every_topic || 0
      return topicCount * postsPerTopic
    },
    copyToClipboard(text) {
      navigator.clipboard.writeText(text).then(() => {
        this.$message.success('已复制到剪贴板')
      }).catch(() => {
        this.$message.error('复制失败')
      })
    },
    askAIToOptimizePrompt() {
      // 触发AI对话，让AI优化Prompt
      this.$message.info('请在左侧对话框中询问AI如何优化Prompt')
    },
    async saveFactory() {
      if (!this.canSave) {
        this.$message.warning('请先完成必填项：任务名称、Prompt模板、话题列表')
        return
      }

      this.saving = true
      try {
        // 新的保存流程：
        // 1. 先保存动态素材（获取IDs）
        // 2. 再保存话题列表（获取IDs）
        // 3. 然后保存Prompt（此时Prompt中已包含实际的Topic IDs）
        // 4. 最后创建AutoPostGenerateTask

        // 1. 保存动态内容组
        const dynamicGroupIds = []
        for (const group of this.factoryData.dynamic_content_groups) {
          const groupResult = await AddFactoryContent({
            action: 'create_group',
            topicstrategy_name: '内容工厂-动态素材',
            group: { name: group.name }
          })
          const groupId = groupResult.data.id
          dynamicGroupIds.push(groupId)

          // 保存该组的素材项
          await AddFactoryContent({
            action: 'update_children',
            topicstrategy_name: '内容工厂-动态素材',
            parent_id: groupId,
            children: group.items.map(item => ({
              description: item,
              isNew: true
            }))
          })
        }

        // 2. 保存话题列表
        const topicFolderResult = await AddFactoryContent({
          action: 'create_group',
          topicstrategy_name: '文章',
          group: { name: this.factoryData.task_name + ' - 话题列表' }
        })
        const topicFolderId = topicFolderResult.data.id

        // 保存子话题
        await AddFactoryContent({
          action: 'update_children',
          topicstrategy_name: '文章',
          parent_id: topicFolderId,
          children: this.factoryData.topics.map(topic => ({
            keyword: topic.keyword,
            title: topic.title,
            description: topic.description,
            isNew: true
          }))
        })

        // 3. 保存Prompt模板到Topic（此时Prompt中应该已包含实际的Topic IDs）
        const promptTopicResult = await SavePromptTopic({
          action: 'save_prompt_topic',
          topicstrategy_name: '内容工厂-prompt',
          title: this.factoryData.task_name + ' - Prompt',
          keyword: this.factoryData.industry,
          description: this.factoryData.prompt_template
        })
        const promptTopicId = promptTopicResult.data.id

        // 4. 保存循环列表（如果启用）
        const loopGroupIds = []
        if (this.factoryData.need_loop_content && this.factoryData.loop_content_groups) {
          for (const group of this.factoryData.loop_content_groups) {
            const groupResult = await AddFactoryContent({
              action: 'create_group',
              topicstrategy_name: '内容工厂-循环列表',
              group: { name: group.name }
            })
            const groupId = groupResult.data.id
            loopGroupIds.push(groupId)

            // 保存该组的列表项
            await AddFactoryContent({
              action: 'update_children',
              topicstrategy_name: '内容工厂-循环列表',
              parent_id: groupId,
              children: group.items.map(item => ({
                description: item,
                isNew: true
              }))
            })
          }
        }

        // 5. 创建AutoPostGenerateTask
        const taskData = {
          name: this.factoryData.task_name,
          prompt_topic_id: promptTopicId,
          topic_folder_id: topicFolderId,
          post_every_topic: this.factoryData.post_every_topic,
          post_period_day: this.factoryData.post_period_day,
          post_number_in_period: this.factoryData.post_number_in_period,
          all_staff: this.factoryData.all_staff,
          staff_tag: this.factoryData.all_staff ? [] : this.factoryData.staff_tag,
          is_finished: false
        }

        await AddAutopostgeneratetask(taskData)

        this.$notify({
          title: '成功',
          message: '内容工厂创建成功！',
          type: 'success',
          duration: 3000
        })

        this.currentStage = 'complete'
        this.$emit('factory-created')
        setTimeout(() => {
          this.dialogVisible = false
        }, 2000)
      } catch (error) {
        console.error('保存失败:', error)
        this.$message.error('保存失败: ' + (error.msg || error.message || '未知错误'))
      } finally {
        this.saving = false
      }
    }
  }
}
</script>

<style scoped>
.factory-data-panel {
  height: calc(100vh - 120px);
  overflow-y: auto;
  padding: 20px;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #EBEEF5;
}

.panel-header h3 {
  margin: 0;
  font-size: 18px;
  display: flex;
  align-items: center;
}

.question-card {
  cursor: pointer;
  transition: all 0.3s;
}

.question-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
</style>
